package cn.edu.fzu.homemaking.helper;

import java.util.ArrayDeque;
import java.util.Deque;

import org.apache.commons.lang3.StringUtils;

/**
 * 将金额转换为汉字
 *
 * @author fangxin
 * @date 2023/3/26
 */
public class MoneyTransferHelper {

    private static final String[] NUM  = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };

    private static final String[] UNIT = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };

    private static final String   ZERO = "0";

    /** 将金额转换为汉字 **/
    public static String transferToChinese(Long amount) {
        String amountStr = amount.toString();
        String[] money = new String[amountStr.length()];
        for (int i = 0; i < amountStr.length(); i++) {
            money[i] = String.valueOf(amountStr.charAt(i));
        }

        StringBuilder builder = new StringBuilder();
        Deque<String> stack = new ArrayDeque<>();
        int j = 0;
        boolean addZero = false;
        for (int i = money.length - 1; i >= 0; i--) {
            if (ZERO.equals(money[i])) {
                //当当前单位为元或万或亿的时候,加入栈中
                if (j == 2 || j == 6 || j == 10) {
                    stack.push(UNIT[j]);
                } else if (addZero) {
                    //加零
                    stack.push(NUM[0]);
                    //连续遇到几个0,只需加一次即可
                    addZero = false;
                }
                //跳过0的时候,单位指针也要继续往后移动
                j++;
                continue;
            }
            //do not use isEmpty to judge this stack is empty,it will let the result be wrong.
            if (stack.size() != 0) {
                builder.append(stack.pop());
            }
            addZero = true;
            builder.append(UNIT[j++]).append(NUM[Integer.valueOf(money[i])]);
        }
        return StringUtils.reverse(builder.toString());
    }

}
